import React, { useState } from 'react';
import { Form, Input, Button, Card, message, Typography, Row, Col } from 'antd';
import { LockOutlined, MobileOutlined, SafetyCertificateOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { useDispatch } from 'react-redux';
import { register, sendSmsCode } from '../../api/auth';
import { setCredentials } from "../../store/slices/authSlice";

// 用户信息接口
interface UserResponse {
  expired_at: number;
  id: number;
  nick_name: string;
  role: number;
  token: string;
}

interface RegisterRequest {
  mobile: string;
  password: string;
  code: string;
}

interface RegisterForm extends RegisterRequest {
  confirmPassword: string;
}

const Register: React.FC = () => {
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const [sendingCode, setSendingCode] = useState(false);
  const [countdown, setCountdown] = useState(0);
  const [form] = Form.useForm();

  // 发送短信验证码
  const handleSendSmsCode = async () => {
    try {
      const mobile = form.getFieldValue('mobile');

      // 验证手机号
      if (!mobile) {
        message.error('请输入手机号');
        return;
      }

      if (!/^1[3-9]\d{9}$/.test(mobile)) {
        message.error('请输入有效的手机号');
        return;
      }

      setSendingCode(true);
      await sendSmsCode(mobile);
      message.success('验证码发送成功');

      // 开始倒计时
      let seconds = 60;
      setCountdown(seconds);

      const timer = setInterval(() => {
        seconds -= 1;
        setCountdown(seconds);
        if (seconds <= 0) {
          clearInterval(timer);
          setSendingCode(false);
        }
      }, 1000);

    } catch (error: any) {
      setSendingCode(false);
      // 显示后端返回的具体错误信息
      if (error.response && error.response.data) {
        const errorData = error.response.data;
        if (typeof errorData === 'object') {
          const errorMessages = Object.values(errorData).join(', ');
          message.error(errorMessages || '发送验证码失败，请稍后重试');
        } else if (typeof errorData === 'string') {
          message.error(errorData);
        } else {
          message.error('发送验证码失败，请稍后重试');
        }
      } else {
        message.error('发送验证码失败，请稍后重试');
      }
    }
  };

  const onFinish = async (values: RegisterForm) => {
    try {
      const { confirmPassword, ...registerData } = values;
      const response = await register(registerData);
      const userData: UserResponse = response;

      // 存储到 localStorage
      localStorage.setItem('token', userData.token);
      localStorage.setItem('user', JSON.stringify({
        id: userData.id,
        nick_name: userData.nick_name,
        role: userData.role,
        expired_at: userData.expired_at
      }));

      // 更新 Redux store
      dispatch(setCredentials({
        user: {
          id: userData.id,
          nick_name: userData.nick_name,
          role: userData.role,
          expired_at: userData.expired_at
        },
        token: userData.token
      }));

      message.success('注册成功，正在跳转到仪表盘...');
      // 使用 setTimeout 来确保消息显示后再跳转
      setTimeout(() => {
        navigate('/dashboard');
      }, 1000);
    } catch (error: any) {
      // 显示后端返回的具体错误信息
      if (error.response && error.response.data) {
        const errorData = error.response.data;
        if (typeof errorData === 'object') {
          const errorMessages = Object.values(errorData).join(', ');
          message.error(errorMessages || '注册失败，请稍后重试');
        } else if (typeof errorData === 'string') {
          message.error(errorData);
        } else {
          message.error('注册失败，请稍后重试');
        }
      } else {
        message.error('注册失败，请稍后重试');
      }
    }
  };

  return (
    <div style={{
      display: 'flex',
      flexDirection: 'column',
      justifyContent: 'center',
      alignItems: 'center',
      minHeight: '100vh',
      background: '#f0f2f5'
    }}>
      <Typography.Title level={2} style={{ marginBottom: '2rem', textAlign: 'center' }}>
        多语言切换管理系统
      </Typography.Title>
      <Card
        title={<div style={{ width: '100%', textAlign: 'center' }}>注册</div>}
        style={{ width: 300 }}
      >
        <Form
          form={form}
          name="register"
          onFinish={onFinish}
        >
          <Form.Item
            name="mobile"
            rules={[
              { required: true, message: '请输入手机号!' },
              { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号!' }
            ]}
          >
            <Input
              prefix={<MobileOutlined />}
              placeholder="手机号"
            />
          </Form.Item>

          <Form.Item
            name="code"
            rules={[{ required: true, message: '请输入验证码!' }]}
          >
            <Row gutter={8}>
              <Col span={16}>
                <Input
                  prefix={<SafetyCertificateOutlined />}
                  placeholder="短信验证码"
                />
              </Col>
              <Col span={8}>
                <Button
                  onClick={handleSendSmsCode}
                  disabled={sendingCode}
                  style={{ width: '100%' }}
                >
                  {countdown > 0 ? `${countdown}s` : '获取验证码'}
                </Button>
              </Col>
            </Row>
          </Form.Item>

          <Form.Item
            name="password"
            rules={[
              { required: true, message: '请输入密码!' },
              { min: 6, message: '密码长度不能少于6个字符!' }
            ]}
          >
            <Input.Password
              prefix={<LockOutlined />}
              placeholder="密码"
            />
          </Form.Item>

          <Form.Item
            name="confirmPassword"
            dependencies={['password']}
            rules={[
              { required: true, message: '请确认密码!' },
              ({ getFieldValue }) => ({
                validator(_, value) {
                  if (!value || getFieldValue('password') === value) {
                    return Promise.resolve();
                  }
                  return Promise.reject(new Error('两次输入的密码不一致!'));
                },
              }),
            ]}
          >
            <Input.Password
              prefix={<LockOutlined />}
              placeholder="确认密码"
            />
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit" style={{ width: '100%' }}>
              注册
            </Button>
            <Button
              type="link"
              onClick={() => navigate('/login')}
              style={{ width: '100%', marginTop: '10px' }}
            >
              已有账号? 去登录
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  );
};

export default Register;